package service

import (
	"context"
	"fmt"
	"srv-server/basic/global"
	__ "srv-server/basic/proto"
	"srv-server/handler/model"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedSrvServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) CreateQuestion(_ context.Context, in *__.CreateQuestionRequest) (*__.CreateQuestionResponse, error) {
	var u model.User
	global.DB.Where("id = ?", in.FounderNum).Find(&u)
	if u.Id == 0 {
		return &__.CreateQuestionResponse{
			Code: 500,
			Msg:  "账号出现错误",
		}, nil
	}
	fmt.Println(u)
	var q model.Questions
	if u.Status == 2 {
		q = model.Questions{

			ExType:         in.ExType,
			MajorOne:       in.MajorOne,
			MajorTwo:       in.MajorTwo,
			Difficulty:     uint(in.Difficulty),
			Author:         in.Author,
			Founder:        in.Founder,
			FounderNum:     int32(in.FounderNum),
			Cretime:        in.Cretime,
			Reviewer:       "",
			ReviewerType:   4,
			ReviewerNumber: "",
			ExName:         in.ExName,
			Option:         uint(in.Option),
			Answer:         uint(in.Answer),
			Keysword:       in.Keysword,
		}
	} else if u.Status == 1 {
		q = model.Questions{

			ExType:         in.ExType,
			MajorOne:       in.MajorOne,
			MajorTwo:       in.MajorTwo,
			Difficulty:     uint(in.Difficulty),
			Author:         in.Author,
			Founder:        in.Founder,
			FounderNum:     int32(in.FounderNum),
			Cretime:        in.Cretime,
			Reviewer:       in.Reviewer,
			ReviewerType:   uint(in.ReviewerType),
			ReviewerNumber: in.ReviewerNumber,
			ExName:         in.ExName,
			Option:         uint(in.Option),
			Answer:         uint(in.Answer),
			Keysword:       in.Keysword,
		}
	} else {
		return &__.CreateQuestionResponse{
			Code: 500,
			Msg:  "账号出现错误",
		}, nil
	}

	err := global.DB.Create(&q).Error
	if err != nil {
		return &__.CreateQuestionResponse{
			Code: 500,
			Msg:  "创建试题失败",
		}, nil
	}
	return &__.CreateQuestionResponse{
		Code: 2000,
		Msg:  "创建试题成功",
	}, nil
}
func (s *Server) InfoQuestion(_ context.Context, in *__.InfoQuestionRequest) (*__.InfoQuestionResponse, error) {
	var q []model.Questions
	query := global.DB.Model(&model.Questions{})
	var u model.User
	query.Where("id = ?", in.QuestionsId).Find(&q)
	global.DB.Where("id = ?", in.QuestionsId).Find(&u)
	var info []*__.InfoQuestion
	if u.Status == 1 {
		for _, i := range q {
			question := __.InfoQuestion{
				ExType:         i.ExType,
				MajorOne:       i.MajorOne,
				MajorTwo:       i.MajorTwo,
				Difficulty:     int64(i.Difficulty),
				Author:         i.Author,
				Founder:        i.Founder,
				FounderNum:     int64(i.FounderNum),
				Cretime:        i.Cretime,
				Reviewer:       "",
				ReviewerType:   0,
				ReviewerNumber: "",
				ExName:         i.ExName,
				Option:         int64(i.Option),
				Answer:         int64(i.Answer),
				Keysword:       i.Keysword,
			}
			info = append(info, &question)
		}
	} else {
		for _, i := range q {
			question := __.InfoQuestion{
				ExType:         i.ExType,
				MajorOne:       i.MajorOne,
				MajorTwo:       i.MajorTwo,
				Difficulty:     int64(i.Difficulty),
				Author:         i.Author,
				Founder:        i.Founder,
				FounderNum:     int64(i.FounderNum),
				Cretime:        i.Cretime,
				Reviewer:       i.Reviewer,
				ReviewerType:   int64(i.ReviewerType),
				ReviewerNumber: i.ReviewerNumber,
				ExName:         i.ExName,
				Option:         int64(i.Option),
				Answer:         int64(i.Answer),
				Keysword:       i.Keysword,
			}
			info = append(info, &question)
		}
	}

	return &__.InfoQuestionResponse{
		Info: info,
	}, nil
}
func (s *Server) FindQuestion(_ context.Context, in *__.FindQuestionRequest) (*__.FindQuestionResponse, error) {
	var q []model.Questions
	query := global.DB.Model(&model.Questions{})
	if in.ExName != "" {

		query.Where("ex_name = ?", in.ExName).Find(&q)
	} else if in.ExType != "" {
		query.Where("ex_type = ?", in.ExType).Find(&q)
	} else if in.ReviewerType != 0 {
		query.Where("reviewer_type = ?", in.ReviewerType).Find(&q)
	} else if in.MajorOne != "" {
		query.Where("major_one = ?", in.MajorOne).Find(&q)
	} else if in.MajorTwo != "" {
		query.Where("major_two = ?", in.MajorTwo).Find(&q)
	} else if in.ReviewerNumber != "" {
		query.Where("reviewer_number = ?", in.ReviewerNumber).Find(&q)
	} else if in.Keysword != "" {
		query.Where("keysword = ?", in.Keysword).Find(&q)
	} else if in.FounderNum != 0 {
		query.Where("founder_num = ?", in.FounderNum).Find(&q)
	}

	var find []*__.FindQuestion

	for _, i := range q {
		question := __.FindQuestion{
			ExType:         i.ExType,
			MajorOne:       i.MajorOne,
			MajorTwo:       i.MajorTwo,
			Difficulty:     int64(i.Difficulty),
			Author:         i.Author,
			Founder:        i.Founder,
			FounderNum:     int64(i.FounderNum),
			Cretime:        i.Cretime,
			Reviewer:       i.Reviewer,
			ReviewerType:   int64(i.ReviewerType),
			ReviewerNumber: i.ReviewerNumber,
			ExName:         i.ExName,
			Option:         int64(i.Option),
			Answer:         int64(i.Answer),
			Keysword:       i.Keysword,
		}
		find = append(find, &question)
	}

	return &__.FindQuestionResponse{
		Find: find,
	}, nil
}
func (s *Server) DelQuestion(_ context.Context, in *__.DelQuestionRequest) (*__.DelQuestionResponse, error) {

	var q model.Questions

	err := global.DB.Where("id = ?", in.Question).Delete(&q).Error
	if err != nil {
		return &__.DelQuestionResponse{
			Code: 500,
			Msg:  "删除试题失败",
		}, nil
	}
	return &__.DelQuestionResponse{
		Code: 200,
		Msg:  "删除试题成功",
	}, nil
}
func (s *Server) UpdateQuestion(_ context.Context, in *__.UpdateQuestionRequest) (*__.UpdateQuestionResponse, error) {

	var q model.Questions

	q = model.Questions{

		ExType:         in.ExType,
		MajorOne:       in.MajorOne,
		MajorTwo:       in.MajorTwo,
		Difficulty:     uint(in.Difficulty),
		Author:         in.Author,
		Founder:        in.Founder,
		FounderNum:     int32(in.FounderNum),
		Cretime:        in.Cretime,
		Reviewer:       in.Reviewer,
		ReviewerType:   uint(in.ReviewerType),
		ReviewerNumber: in.ReviewerNumber,
		ExName:         in.ExName,
		Option:         uint(in.Option),
		Answer:         uint(in.Answer),
		Keysword:       in.Keysword,
	}

	err := global.DB.Where("id = ?", in.QuestionId).Updates(&q).Error
	if err != nil {
		return &__.UpdateQuestionResponse{
			Code: 500,
			Msg:  "试题修改失败",
		}, nil
	}
	return &__.UpdateQuestionResponse{
		Code: 200,
		Msg:  "试题修改成功",
	}, nil
}
func (s *Server) AddPaper(_ context.Context, in *__.AddPaperRequest) (*__.AddPaperResponse, error) {

	var t model.TestPaper

	t = model.TestPaper{

		GroupPaperType: uint(in.GroupPaperType),
		ExName:         in.ExName,
		ExType:         uint(in.ExType),
		ExTime:         in.ExTime,
		ExSort:         uint(in.ExSort),
		OptionSort:     uint(in.OptionSort),
		TotalScore:     uint(in.TotalScore),
		PassScore:      uint(in.PassScore),
		Reviewer:       in.Reviewer,
		ExamNotice:     in.ExamNotice,
	}

	err := global.DB.Create(&t).Error
	if err != nil {
		return &__.AddPaperResponse{
			Code: 500,
			Msg:  "试卷创建失败",
		}, nil
	}
	return &__.AddPaperResponse{
		Code: 200,
		Msg:  "试卷创建成功",
	}, nil
}
func (s *Server) AddTestQues(_ context.Context, in *__.AddTestQuesRequest) (*__.AddTestQuesResponse, error) {
	var t model.TestPaper
	global.DB.Where("id = ?", in.TestPaperId).Find(&t)
	if t.Id == 0 {
		return &__.AddTestQuesResponse{
			Code: 500,
			Msg:  "试卷不存在",
		}, nil
	}
	var q model.TestQuestions
	if t.GroupPaperType == 1 {
		q = model.TestQuestions{

			TestPaperId:       uint(in.TestPaperId),
			Topic:             in.Topic,
			QuestionType:      in.QuestionType,
			Difficulty:        uint(in.Difficulty),
			Keysword:          in.Keysword,
			ProfessionalScope: in.ProfessionalScope,
		}

	} else {
		return &__.AddTestQuesResponse{
			Code: 100000,
			Msg:  "请前往自动组卷",
		}, nil
	}
	err := global.DB.Create(&q).Error
	if err != nil {
		return &__.AddTestQuesResponse{
			Code: 500,
			Msg:  "手动组卷失败",
		}, nil
	}
	return &__.AddTestQuesResponse{
		Code: 200,
		Msg:  "手动组卷成功",
	}, nil
}
func (s *Server) FindTestQues(_ context.Context, in *__.FindTestQuesRequest) (*__.FindTestQuesResponse, error) {
	var q []model.TestQuestions
	query := global.DB.Model(&model.TestQuestions{})
	if in.TestPaperId != 0 {
		query.Where("test_paper_id = ?", in.TestPaperId).Find(&q)
	} else if in.Topic != "" {
		query.Where("topic = ?", in.Topic).Find(&q)
	} else if in.Difficulty != 0 {
		query.Where("difficulty = ?", in.Difficulty).Find(&q)
	} else if in.Keysword != "" {
		query.Where("keysword = ?", in.Keysword).Find(&q)
	} else if in.ProfessionalScope != "" {
		query.Where("professional_scope = ?", in.ProfessionalScope).Find(&q)
	}

	var find []*__.FindTestQues

	for _, i := range q {
		question := __.FindTestQues{
			TestPaperId:       int64(i.TestPaperId),
			Topic:             i.Topic,
			QuestionType:      i.QuestionType,
			Difficulty:        int64(i.Difficulty),
			Keysword:          i.Keysword,
			ProfessionalScope: i.ProfessionalScope,
		}
		find = append(find, &question)
	}

	return &__.FindTestQuesResponse{
		Find: find,
	}, nil
}
func (s *Server) DelTestQues(_ context.Context, in *__.DelTestQuesRequest) (*__.DelTestQuesResponse, error) {
	var q model.TestQuestions

	err := global.DB.Where("id = ?", in.TestQuesId).Delete(&q).Error
	if err != nil {
		return &__.DelTestQuesResponse{
			Code: 500,
			Msg:  "删除试题失败",
		}, nil
	}
	return &__.DelTestQuesResponse{
		Code: 200,
		Msg:  "删除试题成功",
	}, nil
}
func (s *Server) FindTestPaper(_ context.Context, in *__.FindTestPaperRequest) (*__.FindTestPaperResponse, error) {
	var q []model.TestPaper
	query := global.DB.Model(&model.TestPaper{})

	query.Find(&q)

	var find []*__.FindTestPaper

	for _, i := range q {
		question := __.FindTestPaper{
			GroupPaperType: int64(i.GroupPaperType),
			ExName:         i.ExName,
			ExType:         int64(i.ExType),
			ExTime:         i.ExTime,
			ExSort:         int64(i.ExSort),
			OptionSort:     int64(i.OptionSort),
			TotalScore:     int64(i.TotalScore),
			PassScore:      int64(i.PassScore),
			Reviewer:       i.Reviewer,
			ExamNotice:     i.ExamNotice,
		}
		find = append(find, &question)
	}

	return &__.FindTestPaperResponse{
		Find: find,
	}, nil
}
func (s *Server) InfoTestQues(_ context.Context, in *__.InfoTestQuesRequest) (*__.InfoTestQuesResponse, error) {
	var q []model.TestQuestions
	query := global.DB.Model(&model.TestPaper{})

	query.Where("test_paper_id = ?", in.TestPaperId).Find(&q)

	var find []*__.InfoTestQues

	for _, i := range q {
		question := __.InfoTestQues{
			TestPaperId:  int64(i.TestPaperId),
			Topic:        i.Topic,
			QuestionType: i.QuestionType,
			Option:       int64(i.Option),
			Answer:       int64(i.Answer),
			OptionScore:  int64(i.OptionScore),
		}
		find = append(find, &question)
	}

	return &__.InfoTestQuesResponse{
		Info: find,
	}, nil
}
func (s *Server) Register(_ context.Context, in *__.RegisterRequest) (*__.RegisterResponse, error) {
	var st model.Student

	global.DB.Where("mobile = ?", in.Mobile).Find(&st)
	if st.Id == 0 {
		st = model.Student{

			Mobile: in.Mobile,
		}

		err := global.DB.Create(&st).Error
		if err != nil {
			return &__.RegisterResponse{
				Code: 500,
				Msg:  "学员注册失败",
			}, nil
		}

		return &__.RegisterResponse{
			Code: 200,
			Msg:  "学员注册成功",
			Id:   int64(st.Id),
		}, nil
	}
	return &__.RegisterResponse{
		Code: 200,
		Msg:  "学员登录成功",
		Id:   int64(st.Id),
	}, nil
}
func (s *Server) AddExam(_ context.Context, in *__.AddExamRequest) (*__.AddExamResponse, error) {
	var st model.Exam
	var p model.TestPaper

	global.DB.Where("id = ?", in.TestPaperId).Find(&p)
	if p.Id == 0 {
		return &__.AddExamResponse{
			Code: 500,
			Msg:  "试卷不存在",
		}, nil
	}
	st = model.Exam{
		StudentId:      uint(in.StudentId),
		TestPaperId:    uint(in.TestPaperId),
		TestQuestionId: uint(in.TestQuestionId),
		ExamStatus:     uint(in.ExamStatus),
		Score:          in.Score,
		RightWrong:     uint(in.RightWrong),
		StartTime:      uint(in.StartTime),
		EndTime:        uint(in.EndTime),
		ParticipatIn:   uint(in.ParticipatIn),
	}
	err := global.DB.Create(&st).Error
	if err != nil {
		return &__.AddExamResponse{
			Code: 500,
			Msg:  "考试新增失败",
		}, nil
	}

	return &__.AddExamResponse{
		Code: 200,
		Msg:  "考试新增成功",
	}, nil
}
func (s *Server) InfoExam(_ context.Context, in *__.InfoExamRequest) (*__.InfoExamResponse, error) {
	var sts []model.Exam
	var ex model.Exam
	global.DB.Where("student_id = ?", in.StudentId).Find(&ex)
	query := global.DB.Model(&model.Exam{})

	query.Where("student_id = ?", in.StudentId).Find(&sts)

	var info []*__.InfoExam
	if ex.ParticipatIn > 5 {
		ex = model.Exam{

			StudentStatus: 2,
		}
		global.DB.Where("student_id = ?", in.StudentId).Find(&ex)
		return &__.InfoExamResponse{
			Info: nil,
			Msg:  "进入时间超过前五分钟，你已经不可再进入考试",
		}, nil

	}
	if ex.ExamStatus == 3 {
		return &__.InfoExamResponse{
			Info: nil,
			Msg:  "考试还未开始",
		}, nil
	} else if ex.ExamStatus == 2 {
		for _, st := range sts {
			infoExam := __.InfoExam{
				StudentId:      int64(st.StudentId),
				TestPaperId:    int64(st.TestPaperId),
				TestQuestionId: int64(st.TestQuestionId),
				ExamStatus:     int64(st.ExamStatus),
				Score:          st.Score,
				RightWrong:     int64(st.RightWrong),
				StartTime:      int64(st.StartTime),
				EndTime:        int64(st.EndTime),
				ParticipatIn:   int64(st.ParticipatIn),
				StudentStatus:  int64(st.StudentStatus),
			}
			info = append(info, &infoExam)

		}
	} else {
		return &__.InfoExamResponse{
			Info: nil,
			Msg:  "考试进行中，无法查看",
		}, nil
	}

	return &__.InfoExamResponse{
		Info: info,
		Msg:  "展示成功",
	}, nil
}
func (s *Server) AnswerExam(_ context.Context, in *__.AnswerExamRequest) (*__.AnswerExamResponse, error) {
	var ex model.Exam

	ex = model.Exam{

		RightWrong: uint(in.RightWrong),
	}
	err := global.DB.Where("student_id = ? or test_paper_id = ?", in.StudentId, in.TestPaperId).Updates(&ex).Error
	if err != nil {
		return &__.AnswerExamResponse{
			Code: 500,
			Msg:  "答题失败",
		}, nil
	}
	return &__.AnswerExamResponse{
		Code: 200,
		Msg:  "答题成功",
	}, nil
}
func (s *Server) MarkingExam(_ context.Context, in *__.MarkingExamRequest) (*__.MarkingExamResponse, error) {
	var ex model.Exam
	global.DB.Where("student_id = ? or test_paper_id = ?", in.StudentId, in.TestPaperId).Find(&ex)
	if ex.ExamStatus == 2 {
		if ex.RightWrong != 1 {
			ex = model.Exam{

				Score: "0分",
			}
			err := global.DB.Where("student_id = ? or test_paper_id = ?", in.StudentId, in.TestPaperId).Updates(&ex).Error
			if err != nil {
				return &__.MarkingExamResponse{
					Code: 500,
					Msg:  "阅卷操作失败",
				}, nil
			}
		}
	}

	return &__.MarkingExamResponse{
		Code: 200,
		Msg:  "阅卷操作成功",
	}, nil
}
func (s *Server) Transcript(_ context.Context, in *__.TranscriptRequest) (*__.TranscriptResponse, error) {
	var e []model.Exam
	query := global.DB.Model(&model.Exam{})

	query.Where("student_id = ? or test_paper_id = ?", in.StudentId, in.TestPaperId).Find(&e)

	var find []*__.Transcript

	for _, i := range e {
		question := __.Transcript{
			StudentId:     int64(i.StudentId),
			TestPaperId:   int64(i.TestPaperId),
			Score:         i.Score,
			StudentStatus: int64(i.StudentStatus),
		}
		find = append(find, &question)
	}

	return &__.TranscriptResponse{
		Transcript: find,
		Msg:        "查看成绩单成功",
	}, nil
}
